//
//  DXYMusicViewController.m
//  Piece
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "DXYMusicViewController.h"
#import "ZHNetworkHandler.h"
#import "YXJCollectionCell.h"
#import "YXJMusicModel.h"
#import "YXJContentModel.h"
#import "YXJLikeMusicModel.h"
#import "FeHourGlass.h"
#import "XZHMusicPlayView.h"
#import "AppDelegate.h"
#import "AAPullToRefresh.h"
#import "YXJTableView.h"
#import "YXJPushMusicViewController.h"
#import "XZHHomeListViewController.h"
#import "DYJListViewController.h"
#import "XZHSearchViewController.h"
#import "ZHArchiverTools.h"

@interface DXYMusicViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, MusicPlayDelegate, sweipDelegate>

/** 音乐整体界面 */
@property (nonatomic, strong) UICollectionView *collectionView;

@property (strong, nonatomic) FeHourGlass *hourGlass;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayOut;

@property (nonatomic, assign) NSInteger pageStart;

@property (nonatomic, assign) NSInteger idList;

@property (nonatomic, strong) NSMutableArray *idListDataSource;

@property (nonatomic, strong) NSMutableArray *commentDataSoucre;

@property (nonatomic, strong) NSMutableArray *likeMusicDataSource;

/** 网络数据model */
@property (nonatomic, strong) YXJMusicModel *musicModel;

@property (nonatomic, strong) YXJContentModel *contentModel;

@property (nonatomic, assign) NSInteger pageNumber;

@property (nonatomic, strong) NSMutableArray *indexArr;


@end

@implementation DXYMusicViewController

-(void)dealloc
{
    self.collectionView.delegate = nil;
    self.collectionView.dataSource = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatCollectionView];
    [self setUpLeftRefreshView];
//    [self setUpRightReloadView];
    self.indexArr = [NSMutableArray array];
    
    [self getDataByPageStart:0];
    __weak DXYMusicViewController *dVC = self;
    _block_way = ^(NSInteger number){
        [dVC getDataByIdNumber:number];
        [dVC getCommentDataByIdNumber:number];
        [dVC getLikeMusicByIdNumber:number];
    };
    [self createTitle:@"音乐"];
    [self createNavigationBarButtonWithPicture:@"plant" Picture:@"play"];
}

#pragma mark 向左刷新小球的方法:
- (void)setUpLeftRefreshView {
    __weak DXYMusicViewController *weakSelf = self;
    AAPullToRefresh *pullToRefreshLeft = [self.collectionView addPullToRefreshPosition:AAPullToRefreshPositionLeft actionHandler:^(AAPullToRefresh *left) {
        [left performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
        
        [weakSelf.collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
        weakSelf.flowLayOut.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 49 - 64 -40);
        weakSelf.flowLayOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        [weakSelf.collectionView reloadData];
    }];
    
    pullToRefreshLeft.threshold = 60;
    //小圈的颜色:
    pullToRefreshLeft.borderColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
    pullToRefreshLeft.borderWidth = 4;
    pullToRefreshLeft.imageIcon = [UIImage new];
}

//#pragma mark 向右刷新的方法
//- (void)setUpRightReloadView
//{
//    __weak DXYMusicViewController *weakSelf = self;
//    AAPullToRefresh *pullToRefreshRight = [self.collectionView addPullToRefreshPosition:AAPullToRefreshPositionRight actionHandler:^(AAPullToRefresh *right) {
//        [right performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
////        DYJListViewController *listVC = [[DYJListViewController alloc] init];
////        [weakSelf.navigationController pushViewController:listVC animated:YES];
//        
//        weakSelf.flowLayOut.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 49 - 64 -40);
//        weakSelf.flowLayOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
//    }];
//    pullToRefreshRight.threshold = 60;
//    //小圈的颜色:
//    pullToRefreshRight.borderColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
//    pullToRefreshRight.borderWidth = 4;
//    pullToRefreshRight.imageIcon = [UIImage new];
//}


#pragma mark -- 初始化collectionView
- (void)creatCollectionView
{
    self.flowLayOut = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayOut.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 113);
    self.flowLayOut.minimumLineSpacing = 0;
    self.flowLayOut.minimumInteritemSpacing = 0;
    self.flowLayOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.flowLayOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 113) collectionViewLayout:self.flowLayOut];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = YES;
    [self.view addSubview:self.collectionView];
}

#pragma mark -- 网络数据解析(获取pageStart)
- (void)getDataByPageStart:(NSInteger)pageStart
{
    self.idListDataSource = [NSMutableArray array];
    
    NSString *urlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/idlist/%ld", pageStart];
    
    [ZHNetworkHandler getDataByURLString:urlString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
        
        //加载动画
        _hourGlass = [[FeHourGlass alloc] initWithView:self.collectionView];
        [self.view addSubview:_hourGlass];
        [_hourGlass showWhileExecutingBlock:^{
            [self myTask];
        } completion:^{
            
        }];
        
        self.idListDataSource = [result objectForKey:@"data"];
        
        [self.collectionView reloadData];
        
        _block_way([[self.idListDataSource objectAtIndex:0]integerValue]);
        
        for (NSInteger i = 0; i < self.idListDataSource.count; i++) {
            [self.collectionView registerClass:[YXJCollectionCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"cell%ld", i]];
        }
        
    } WithFailure:^(NSError *error) {
        _hourGlass = [[FeHourGlass alloc] initWithView:self.collectionView];
        [self.view addSubview:_hourGlass];
        [_hourGlass showWhileExecutingBlock:^{
            [self myTask];
        } completion:^{
            
        }];
    }];
}

- (void)myTask
{
    sleep(6);
}

#pragma mark -- 网络解析(获取头视图)
- (void)getDataByIdNumber:(NSInteger)idNumber
{
    NSString *urlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%ld", idNumber];
        [ZHNetworkHandler getDataByURLString:urlString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
        
        //数据缓存
        [ZHArchiverTools archiverObject:result ByKey:@"homeCache" WithPath:@"home.plist"];
        NSDictionary *diction = [result objectForKey:@"data"];
        
        self.musicModel = [[YXJMusicModel alloc] initWithDic:diction];
        [self.collectionView reloadData];
        [_hourGlass removeFromSuperview];
        
    } WithFailure:^(NSError *error) {
        
        NSDictionary *dic = (NSDictionary *)[ZHArchiverTools unarchiverObjectByKey:@"homeCache" WithPath:@"home.plist"];
        if (dic == nil) {
            
        }
        else
        {
            self.musicModel = [[YXJMusicModel alloc] initWithDic:dic];
            if (_musicModel.platform == 1) {
                _musicModel.music_id = @"http://audio.xmcdn.com/group4/M02/10/EF/wKgDtFMnpi6Ais1VAA6eW1LeOVg178.mp3";
            }
            [self.collectionView reloadData];
//            [_hourGlass removeFromSuperview];
        }
          }];
}

#pragma mark -- 网络解析(获取评论数据)
- (void)getCommentDataByIdNumber:(NSInteger)idNumber
{
    self.commentDataSoucre = [NSMutableArray array];
    
    NSString *commentString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praise/music/%ld/0", idNumber];
    
    [ZHNetworkHandler getDataByURLString:commentString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
        
        //数据缓存
        [ZHArchiverTools archiverObject:result ByKey:@"homeCache" WithPath:@"home.plist"];
        
        NSDictionary *diction = [result objectForKey:@"data"];
        
        NSArray *array = [diction objectForKey:@"data"];
        
        for (NSDictionary *dic in array) {
            
            YXJContentModel *model = [[YXJContentModel alloc] initWithDic:dic];
            
            [self.commentDataSoucre addObject:model];
        }
        YXJContentModel *nilModel = [[YXJContentModel alloc] init];
        [self.commentDataSoucre insertObject:nilModel atIndex:0];
        
        [self.collectionView reloadData];
        
    } WithFailure:^(NSError *error) {
        NSDictionary *dic = (NSDictionary *)[ZHArchiverTools unarchiverObjectByKey:@"homeCache" WithPath:@"home.plist"];
        if (dic == nil) {
            
        }
        else
        {
            
            NSDictionary *diction = [dic objectForKey:@"data"];
            
            NSArray *array = [diction objectForKey:@"data"];
            
            for (NSDictionary *dic in array) {
                
                YXJContentModel *model = [[YXJContentModel alloc] initWithDic:dic];
                
                [self.commentDataSoucre addObject:model];
            }
            YXJContentModel *nilModel = [[YXJContentModel alloc] init];
            [self.commentDataSoucre insertObject:nilModel atIndex:0];
            
            [self.collectionView reloadData];
            
        }
    }];
}

#pragma mark -- 网络解析(获取相似歌曲数据)
- (void)getLikeMusicByIdNumber:(NSInteger)IdNumber
{
    self.likeMusicDataSource = [NSMutableArray array];
    
    NSString *likeUrlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/related/music/%ld", IdNumber];
    [ZHNetworkHandler getDataByURLString:likeUrlString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
       
        //数据缓存
        [ZHArchiverTools archiverObject:result ByKey:@"homeCache" WithPath:@"home.plist"];
        
        NSArray *array = [result objectForKey:@"data"];
        
        for (NSDictionary *diction in array) {
            
            YXJLikeMusicModel *model = [[YXJLikeMusicModel alloc] initWithDic:diction];
            
            [self.likeMusicDataSource addObject:model];
        }
        YXJLikeMusicModel *nilModel = [[YXJLikeMusicModel alloc] init];
        [self.likeMusicDataSource insertObject:nilModel atIndex:0];
        
        [self.collectionView reloadData];
    } WithFailure:^(NSError *error) {
        
        NSDictionary *dic = (NSDictionary *)[ZHArchiverTools unarchiverObjectByKey:@"homeCache" WithPath:@"home.plist"];
        if (dic == nil) {
            
        }
        else
        {
            NSArray *array = [dic objectForKey:@"data"];
            
            for (NSDictionary *diction in array) {
                
                YXJLikeMusicModel *model = [[YXJLikeMusicModel alloc] initWithDic:diction];
                
                [self.likeMusicDataSource addObject:model];
            }
            YXJLikeMusicModel *nilModel = [[YXJLikeMusicModel alloc] init];
            [self.likeMusicDataSource insertObject:nilModel atIndex:0];
            
            [self.collectionView reloadData];
        }
    }];
}

#pragma mark -- 播放音乐代理方法
- (void)musicPlay
{
    NSInteger idNumber = [[_idListDataSource objectAtIndex:_pageNumber] integerValue];
    
    [self getDataByIdNumber:idNumber];
    AppDelegate *appDelegate = [AppDelegate shareDetailViewController];
    appDelegate.musicInfo = _musicModel;
    
    [[XZHMusicPlayView shareMusicPlayViewInstance] setIndex:_pageNumber];
    [[XZHMusicPlayView shareMusicPlayViewInstance] setMusicArr:_idListDataSource];
    [[XZHMusicPlayView shareMusicPlayViewInstance] setIsPlay:YES];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] pauseButton] setHidden:NO];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] playButton] setHidden:YES];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] titleLabel] setText:_musicModel.title];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] titleLabel] setFont:[UIFont systemFontOfSize:17]];
}

#pragma mark -- collectinView 的协议方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.idListDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    YXJCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"cell%ld", indexPath.row] forIndexPath:indexPath];
    self.pageNumber = indexPath.row;
    cell.model = self.musicModel;
    cell.contentDataSource = self.commentDataSoucre;
    cell.likeMusciDataSource = self.likeMusicDataSource;
    cell.tableView.contentView.delegate = self;
    cell.tableView.delegate = self;

    __weak DXYMusicViewController  *vc = self;
    cell.block = ^(NSInteger num, NSUInteger pageID)
    {        
        YXJPushMusicViewController *mVC = [[YXJPushMusicViewController alloc] init];
        mVC.indextID = num;
        mVC.pageID = pageID;
        [vc.navigationController pushViewController:mVC animated:YES];
    };
    
    cell.clickBlock = ^()
    {        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"index" object:[NSString stringWithFormat:@"%ld", indexPath.row]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:[NSString stringWithFormat:@"%ld", self.musicModel.platform]];
        if (self.musicModel.platform == 1) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该首歌曲由于版权暂时无法播放" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    };
    cell.tableView.contentView.otherNum = indexPath.row;
    
    return cell;
}

#pragma mark -- 滚动方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.commentDataSoucre removeAllObjects];
    [self.likeMusicDataSource removeAllObjects];
    self.musicModel = nil;
}

#pragma mark -- 实现滚动的协议方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger idNumber = [[_idListDataSource objectAtIndex:_pageNumber] integerValue];
    
    [self getDataByIdNumber:idNumber];

    [self getLikeMusicByIdNumber:idNumber];
    
    [self getCommentDataByIdNumber:idNumber];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    //音乐播放页带到最前面
    //[self.view bringSubviewToFront:self.playView];
    [_hourGlass showWhileExecutingBlock:^{
        //[self myTask];
    } completion:^{
        
    }];
}

#pragma mark -- 滑动的代理方法
- (void)sweipWay{
    XZHSearchViewController *searchVC = [[XZHSearchViewController alloc] init];
    
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
